package com.seahorse.youliao.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.seahorse.youliao.common.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ProjectName: youliao
 * @Package: com.seahorse.youliao.security
 * @ClassName: MyAuthenticationFailureHandler
 * @Description: 自定义认证失败处理器
 * @author:songqiang
 * @Date:2020-11-26 15:51
 **/
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /**
     * Called when an authentication attempt fails.
     *
     * @param request   the request during which the authentication attempt occurred.
     * @param response  the response.
     * @param exception the exception which was thrown to reject the authentication
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {


        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        ResponseEntity respBean = ResponseEntity.error(exception.getMessage());
        //封装异常描述信息
        String json = JSONObject.toJSONString(respBean);
        out.write(json);
        out.flush();
        out.close();
    }
}
